package com.miracle.login.module.mvp.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.miracle.basemvp.AppConfig;
import com.miracle.basemvp.base.BaseActivity;
import com.miracle.basemvp.base.state.StateController;
import com.miracle.basemvp.di.component.AppComponent;
import com.miracle.basemvp.network.download.ProgressDownloadListener;
import com.miracle.basemvp.util.FileUtils;
import com.miracle.common.CommonConfig;
import com.miracle.common.state.user.LogOutState;
import com.miracle.common.state.user.LoginContext;
import com.miracle.common.util.PreferencesUtils;
import com.miracle.common.util.S;
import com.miracle.common.util.TWather;
import com.miracle.common.util.Utils;
import com.miracle.common.util.VersionUtil;
import com.miracle.common.view.BaseDialogProvider;
import com.miracle.login.R;
import com.miracle.login.R2;
import com.miracle.login.module.di.component.DaggerLoginComponent;
import com.miracle.login.module.di.module.LoginModule;
import com.miracle.login.module.mvp.contract.LoginContract;
import com.miracle.login.module.mvp.entity.request.LoginRequest;
import com.miracle.login.module.mvp.presenter.LoginPresenter;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * 登陆界面
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View,
        View.OnClickListener, ProgressDownloadListener {
    LifecycleProvider<ActivityEvent> lifecycleProvider;
    @BindView(R2.id.tet_name)
    TextInputEditText mTetName;
    @BindView(R2.id.tet_pwd)
    TextInputEditText mTetPwd;
    @BindView(R2.id.tv_login)
    TextView mTvLogin;
    @BindView(R2.id.et)
    EditText mEtIp;
    @BindView(R2.id.ll_dev)
    LinearLayout mLLDev;
    @BindView(R2.id.tv_version)
    TextView mTvVersion;
    @BindView(R2.id.iv_check)
    ImageView mIvCheck;
    @BindView(R2.id.iv_has_newversion)
    ImageView mIvHasNewVersion;

    @Override
    public int setLayoutId(@Nullable Bundle bundle) {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        String userName = PreferencesUtils.getPreferences(mContext, PreferencesUtils.State
                .USER_NAME);
        mTetName.setText(userName);
        String versionName = VersionUtil.getLocalVersionName(mContext);
        if (CommonConfig.DEBUG) {
            mTvVersion.setText("内测版本 " + versionName);
        } else {
            mTvVersion.setText("正式版本 " + versionName);
        }
        checkVersion();
    }

    @Override
    public void initData() {
    }

    @Override
    public void initStateController() {
        super.initStateController();
    }

    @Override
    public void setDaggerComponent(AppComponent appComponent) {
        DaggerLoginComponent
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onRequest(LifecycleProvider<ActivityEvent> lifecycleProvider) {
        this.lifecycleProvider = lifecycleProvider;
    }

    @OnClick({R2.id.tv_login, R2.id.tv_register, R2.id.tv_save, R2.id.iv_logo, R2.id.iv_check})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_logo) {
            onDisplaySettingButton();
        }
        if (id == R.id.tv_save) {
            String ip = mEtIp.getText().toString().trim();
            AppConfig.BASE_URL = ip;
        }
        if (id == R.id.tv_register) {
            showActivity(new Intent(mContext, RegisterActivity.class));
        }

        //检查更新
        if (id == R.id.iv_check) {
            mPresenter.checkVersion(lifecycleProvider);
        }

        if (id == R.id.tv_login) {
//            ARouter.getInstance()
//                    .build("/main/MainActivity")
//                    .navigation();

            String name = mTetName.getText().toString().trim();
            String pwd = mTetPwd.getText().toString().trim();

            String[] strs = {name, pwd};
            String[] mentions = {"昵称", "密码"};

            if (Utils.checkNullList(mTvLogin, strs, mentions)) {
                return;
            }

            LoginRequest request = new LoginRequest();
            request.setUserName(name);
            request.setPassWord(pwd);

            mPresenter.login(lifecycleProvider, request);
        }
    }

    @Override
    public void loginSucc() {
        ARouter.getInstance()
                .build("/main/MainActivity")
                .navigation();
        finish();
    }

    @Override
    public void FindANewVersion(String msg) {
        checkVersion();
        showUpdateDialog(msg);
    }

    @Override
    public void NoNewVersion() {
        S.Short(mTvLogin, "已经是最新版本").info().show();
    }

    BaseDialogProvider mUpdateDialogProvider;
    AlertDialog mUpdateDialog;

    public void showUpdateDialog(String msg) {
        if (mUpdateDialog == null) {
            mUpdateDialogProvider = new BaseDialogProvider(mContext);
            mUpdateDialog = mUpdateDialogProvider.createDialog(R.layout
                    .dialog_common_mention_single_message);
        }
        ((TextView) mUpdateDialogProvider.getView(R.id.tv_title)).setText("检查更新");
        ((TextView) mUpdateDialogProvider.getView(R.id.tv_dialog_message)).setText(msg);
        mUpdateDialogProvider.getView(R.id.tv_dialog_cancel).setOnClickListener(this);
        mUpdateDialogProvider.getView(R.id.tv_dialog_ok).setOnClickListener(this);
        mUpdateDialog.show();
    }


    /**
     * 设置点击按钮是否可以点击
     * @param enable 是否可以点击
     */
    public void setLoginEnable(boolean enable) {
        mTvLogin.setEnabled(enable);
    }

    @Override
    public void showData(Object o) {

    }

    long[] mHits = null;

    public void onDisplaySettingButton() {
        if (mHits == null) {
            mHits = new long[5];
        }
        //把从第二位至最后一位之间的数字复制到第一位至倒数第一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //记录一个时间
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        //一秒内连续点击。
        if (SystemClock.uptimeMillis() - mHits[0] <= 1000) {
            mHits = null;
            if (mLLDev.getVisibility() == View.VISIBLE) {
                mLLDev.setVisibility(View.GONE);
            } else {
                mLLDev.setVisibility(View.VISIBLE);
            }

        }
    }

    private void testOpenGl() {
        GLSurfaceView surfaceView = new GLSurfaceView(mContext);

    }

    private void checkVersion() {
        int currVersion = VersionUtil.getLocalVersion(mContext);
        int newestVersion = PreferencesUtils.getIntPreferences(mContext, PreferencesUtils.Version
                .VERSION_NEWEST);
        if (currVersion < newestVersion) {
            mIvHasNewVersion.setVisibility(View.VISIBLE);
        } else {
            mIvHasNewVersion.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_dialog_cancel) {
            //隐藏更新提示dialog
            if (mUpdateDialog != null && mUpdateDialog.isShowing()) {
                mUpdateDialog.dismiss();
            }
        }

        if (id == R.id.tv_dialog_ok) {
            //隐藏更新提示dialog
            if (mUpdateDialog != null && mUpdateDialog.isShowing()) {
                mUpdateDialog.dismiss();
            }
            showProgressDialog();
            requestPermission();
        }
    }


    BaseDialogProvider mProgressProvider;
    AlertDialog mProgressDialog;
    ProgressBar mDownloadProgress;

    /**
     * 下载进度dialog
     */
    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressProvider = new BaseDialogProvider(mContext);
            mProgressDialog = mProgressProvider.createDialog(R.layout
                    .dialog_common_progress);
        }
        ((TextView) mProgressProvider.getView(R.id.tv_title)).setText("下载进度");
        mDownloadProgress = mProgressProvider.getView(R.id.dialog_progress);
        mProgressProvider.getView(R.id.tv_dialog_cancel).setVisibility(View.GONE);
        mProgressProvider.getView(R.id.tv_dialog_ok).setVisibility(View.GONE);
        mProgressDialog.show();
    }

    public void requestPermission() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            mPresenter.downloadApk(lifecycleProvider, "", LoginActivity.this);
                        } else {
                        }
                    }
                });
    }

    @Override
    public void onStartDownload() {
        S.Short(mTvLogin, "开始下载").warning().show();
        Log.d("WJQ", "onStartDownload");
    }

    @Override
    public void onProgress(int i) {
        if (mDownloadProgress != null && i > 0) {
            mDownloadProgress.setProgress(i);
        }
    }

    @Override
    public void onFinishDownload() {
        S.Short(mTvLogin, "下载完成").warning().show();
        Log.d("WJQ", "onFinishDownload");
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        String filePath = Environment.getExternalStorageDirectory() + "/WeCloud/wecloud.apk";
        String provider = "com.miracle.cloud.fileprovider";
        FileUtils.installApk(mContext, filePath, provider);
    }

    @Override
    public void onFail(String s) {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        S.Short(mTvLogin, "下载失败: " + s).warning().show();
        Log.d("WJQ", "onFail");
    }


}
